<template>
  <div class="box">
    <div class="aside">
      <div id="group" class="group_navigate">
        <!-- 选手列表 -->
        <button v-for="(item, index) in group_num" :key="index" @click="changeInfo(index)">
          第{{ index + 1 }}位选手
        </button>
      </div>
    </div>
    <div class="group_main">
      <!-- 选手信息展示区 -->
      <div class="title">
        {{ active_name }}
      </div>
      <div class="group_name">{{ group_name }}号选手</div>
      <div>{{ context }}</div>
      <div class="time">
        {{ time_first + ':' + time_second }}
      </div>
      <div class="operate_button">
        <button class="bt1" @click="startOrStop">{{ startButton }}</button>
        <button id="bt2" class="bt2" @click="overTime">{{ overButton }}</button>
        <button class="bt3" @click="createBackWindow">背景窗口</button>
        <button class="bt4" @click="createTimeWindow">计时窗口</button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { useRoute } from 'vue-router'
import { ref, onMounted, onUnmounted } from 'vue'
import './Console_group.css'
import router from '../../router'

const list = ref([])
const active_name = ref('')

const roomId = ref('')
const dataFiles = ref([])
let xuanshou = []
const group_num = ref()

onMounted(() => {
  const route = useRoute()
  roomId.value = route.query.roomId
  getDataFiles()
  window.electron.on('reqMessage-to-console', () => {
    returnMessage(dataFiles.value)
  })
  // 进入房间后自动点击第一个按钮
  setTimeout(() => {
    changeInfo(0)
  }, 10)
})

function returnMessage(data) {
  const Data = JSON.parse(JSON.stringify(data))
  window.electron.resBackToMain(Data)
}

async function getDataFiles() {
  // 使用Electron的IPC通信获取文件列表
  list.value = await window.electron.getDataFiles(roomId.value)
  dataFiles.value = list.value.data[0]
  active_name.value = dataFiles.value.active_name
  time_first.value = dataFiles.value.time
  if (dataFiles.value.xuanshou.length === 0) {
    group_num.value = dataFiles.value.group_num
  } else {
    group_num.value = dataFiles.value.xuanshou.length
    xuanshou = dataFiles.value.xuanshou
  }
  x.value = dataFiles.value.time
  // 初始化选手信息
  createGroup()
}

const group_name = ref()
const time_first = ref()
const initial_time = ref()
const time_second = ref(0 + '0')

const startButton = ref('开始')
const overButton = ref('结束')
const group = ref([])

// 初始化数组
function createGroup() {
  if (xuanshou.length !== 0) {
    for (let i = 0; i < group_num.value; i++) {
      group.value.push({
        name: '' + xuanshou[i].id,
        time_first: time_first.value,
        time_second: 0,
        positive: true
      })
    }
  } else {
    for (let i = 0; i < group_num.value; i++) {
      group.value.push({
        name: '' + (i + 1),
        time_first: time_first.value,
        time_second: 0,
        positive: true
      })
    }
  }
  group_name.value = group.value[0].name
  initial_time.value = time_first.value
}

//读取参数 x为分钟，y为秒
const x = ref()
const y = ref(0)
const isPositive = ref(true)
const isRunTime = ref(false)
const isExist = ref(true)
const intervalId = ref(null) // 存储定时器id
function runTime() {
  intervalId.value = setInterval(() => {
    isRunTime.value = true
    //如果不是在暂停状态
    if (startButton.value === '暂停') {
      if ((isPositive.value = group.value[index_current.value].positive)) {
        if (x.value > 0 && y.value === 0) {
          x.value -= 1
          y.value = 59
        } else {
          y.value -= 1
        }
      }

      if (!isPositive.value) {
        y.value += 1
        if (y.value === 59) {
          x.value += 1
          y.value = 0
        }
      }

      // 当x，y值都为0时
      if (x.value === 0 && y.value === 0) {
        isPositive.value = false
        group.value[index_current.value].positive = false
      }

      if (x.value < 10) {
        time_first.value = '0' + x.value
      } else {
        time_first.value = '' + x.value
      }
      if (y.value < 10) {
        time_second.value = '0' + y.value
      } else {
        time_second.value = '' + y.value
      }

      // 将 time 值传给页面
      window.electron.timeToTime([
        time_first.value,
        time_second.value,
        group_name.value,
        isPositive.value,
        active_name.value
      ])
    }
    if (!isExist.value) {
      // 销毁定时器
      clearInterval(intervalId.value)
    }
  }, 1000)
}

function startOrStop() {
  const group_list = document.getElementById('group')
  switch (startButton.value) {
    case '开始':
      if (!isRunTime.value) {
        runTime()
        recognition.start()
      }
      startButton.value = '暂停'
      break
    case '暂停':
      startButton.value = '继续'
      break
    case '继续':
      startButton.value = '暂停'
      break
    case '重置':
      startButton.value = '开始'
      overButton.value = '结束'
      x.value = initial_time.value
      y.value = 0
      isPositive.value = true
      group.value[index_current.value].positive = true
      // 将值传给Time页面
      if (x.value < 10) {
        time_first.value = '0' + x.value
      } else {
        time_first.value = '' + x.value
      }
      if (y.value < 10) {
        time_second.value = '0' + y.value
      } else {
        time_second.value = y.value
      }
      // 将值传给Time页面
      window.electron.changeInfo({
        group_name: group_person.value.name,
        index: index_current.value,
        time_first: time_first.value,
        time_second: time_second.value
      })
      group_list.children[index_current.value].style.background = '#ff7500'
      break
  }

  group.value[index_current.value].time_first = x.value
  group.value[index_current.value].time_second = y.value
}

//打开背景窗口
function createBackWindow() {
  window.electron.createBackWindow()
}

//打开计时窗口
function createTimeWindow() {
  window.electron.createTimeWindow()
}

const index_current = ref(0)
const group_person = ref([])
function changeInfo(index_value) {
  // 保存当前选手信息
  group.value[index_current.value].time_first = x.value
  group.value[index_current.value].time_second = y.value
  //点击按钮后切换选手信息
  index_current.value = index_value
  group_person.value = group.value[index_current.value]
  group_name.value = group_person.value.name

  const group_list = document.getElementById('group')
  // 修改当前按钮边框
  group_list.children[index_current.value].style.border = '4px solid rgba(255, 0, 0, 0)'
  for (let i = 0; i < group.value.length; i++) {
    group_list.children[i].style.border = '4px solid rgba(255, 255, 255, 0)'
  }
  group_list.children[index_current.value].style.border = '4px solid rgba(255, 0, 0, 0.521)'

  x.value = group_person.value.time_first
  y.value = group_person.value.time_second

  isPositive.value = group_person.value.positive

  // 将 x，y 值传给页面
  if (x.value < 10) {
    time_first.value = '0' + x.value
  } else {
    time_first.value = '' + x.value
  }
  if (y.value < 10) {
    time_second.value = '0' + y.value
  } else {
    time_second.value = y.value
  }
  startButton.value = '开始'
  overButton.value = '结束'
  // 将值传给Time页面
  window.electron.changeInfo({
    group_name: group_person.value.name,
    index: index_current.value,
    time_first: time_first.value,
    time_second: time_second.value
  })
}

// 结束计时，将值赋给上一个选手，跳转下一个选手
function overTime() {
  if (overButton.value === '结束') {
    const group_list = document.getElementById('group')
    group_list.children[index_current.value].style.background = '#80808070'
    startOrStop()
    startButton.value = '重置'
    recognition.stop()
    if (group.value[index_current.value + 1] !== undefined) {
      overButton.value = '下一位'
    } else {
      overButton.value = '返回首页'
    }
  } else if (overButton.value === '下一位') {
    if (group.value[index_current.value + 1] !== undefined) {
      // 第二次：切换选手信息
      group.value[index_current.value].time_first = x.value
      group.value[index_current.value].time_second = y.value
      changeInfo(index_current.value + 1)
    }
  } else if (overButton.value === '返回首页') {
    router.push('/start')
  }
}

onUnmounted(() => {
  // 销毁计时器
  isExist.value = false
})

let SpeechRecognition = window.webkitSpeechRecognition
let recognition
let context = ref('')

// 初始化recognition
if (SpeechRecognition) {
  recognition = new SpeechRecognition()
  recognition.continuous = true
  recognition.interimResults = true
  recognition.lang = 'zh-CN'
} else {
  console.error('当前浏览器不支持语音识别')
}

recognition.addEventListener('result', (event) => {
  let result = ''
  for (let i = 0; i < event.results.length; i++) {
    result += event.results[i][0].transcript
  }
  context.value = result
})
</script>
